package com.yellowpage.white.util;




import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class PasswordUtil {

	private static final Log log = LogFactory.getLog(PasswordUtil.class);
	
	public static String encodingByMd5(String password) {	
		
		// 等效于上述代码
		Md5PasswordEncoder mpe = new Md5PasswordEncoder();		
		mpe.setEncodeHashAsBase64(true);		
		
		return mpe.encodePassword(password, "yellowpage").toString();
		
		
	}
	
	public static void processMd5() {
		System.out.println("以MD5方式加密......................");
		
		// 直接指定待采用的加密算法（MD5）
		MessageDigestPasswordEncoder mdpeMd5 = new MessageDigestPasswordEncoder("MD5");
		// 生成32位的Hex版, 这也是encodeHashAsBase64的默认值
		mdpeMd5.setEncodeHashAsBase64(false);
		System.out.println(mdpeMd5.encodePassword("super", "guanghua"));
		// 生成24位的Base64版
		mdpeMd5.setEncodeHashAsBase64(true);
		System.out.println(mdpeMd5.encodePassword("super", "guanghua"));
		
		// 等效于上述代码
		Md5PasswordEncoder mpe = new Md5PasswordEncoder();
		mpe.setEncodeHashAsBase64(false);
		System.out.println(mpe.encodePassword("super", "guanghua"));
		mpe.setEncodeHashAsBase64(true);
		System.out.println(mpe.encodePassword("super", "guanghua"));
	}
	
	public static void processSha() {
		System.out.println("以SHA方式加密......................");
		
		// 直接指定待采用的加密算法（SHA）及加密强度（256）
		MessageDigestPasswordEncoder mdpeSha = new MessageDigestPasswordEncoder("SHA-256");
		mdpeSha.setEncodeHashAsBase64(false);
		System.out.println(mdpeSha.encodePassword("password", null));
		mdpeSha.setEncodeHashAsBase64(true);
		System.out.println(mdpeSha.encodePassword("password", null));
		
		// 等效于上述代码
		ShaPasswordEncoder spe = new ShaPasswordEncoder(256);		
		spe.setEncodeHashAsBase64(false);
		System.out.println(spe.encodePassword("password", null));
		spe.setEncodeHashAsBase64(true);
		System.out.println(spe.encodePassword("password", null));
	}
	
	public static void processSalt() {
		System.out.println("以MD5方式加密、加私钥(盐)......................");
		
		Md5PasswordEncoder mpe = new Md5PasswordEncoder();
		mpe.setEncodeHashAsBase64(false);
		
		// 等效的两行地代码
		System.out.println(mpe.encodePassword("super{guanghua}", null)); // javaee为密码私钥
		System.out.println(mpe.encodePassword("super", "guanghua")); // javaee为密码私钥
		// 结果：87ce7b25b469025af0d5c6752038fb56
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		processMd5();
//		processSha();
		processSalt();
		
		System.out.println(encodingByMd5("super"));
	}

}
